package com.publish.file.controller;

import java.net.URLEncoder;
import java.util.List;

import javax.validation.constraints.NotEmpty;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.publish.file.common.DateUtils;
import com.publish.file.repository.packages.entity.PackageEntityExt;
import com.publish.file.repository.product.entity.ProductEntity;
import com.publish.file.repository.product.entity.ProductExt;
import com.publish.file.service.packages.PackageManagerService;

@CrossOrigin
@Validated
@RestController
@RequestMapping("/apk")
public class ApkRestController {

	@Autowired
	PackageManagerService packageManagerServiceImpl;
//	private Logger logger = LoggerFactory.getLogger(getClass().getSimpleName());

	@RequestMapping("/product/query")
	public Result<List<ProductExt>> queryProducts() {
		try {
			return Result.success(packageManagerServiceImpl.getProducts());
		} catch (Exception e) {
			e.printStackTrace();
			return Result.fail(Result.CODE_QUERY_ERROR, "查询失败");
		}
	}

	@PreAuthorize("hasAnyAuthority('DEV')")
	@RequestMapping("/product/update")
	public Result<String> updateProduct(@RequestParam("name") @NotEmpty(message = "不能为空") String name,
			@RequestParam("id") Long id) {
		try {
			packageManagerServiceImpl.updateProduct(id, name);
			return Result.success("更新成功!");
		} catch (Exception e) {
			e.printStackTrace();
			return Result.fail(Result.CODE_GEN_TOKEN, "系统错误");
		}
	}

	@PreAuthorize("hasAnyAuthority('DEV')")
	@RequestMapping("/product/delete")
	public Result<String> deleteProduct(@RequestParam("id") Long pid) {
		try {
			packageManagerServiceImpl.deleteProduct(pid);
			return Result.success("删除成功!");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Result.fail(Result.CODE_SQL_ERROR, "删除失败!");
	}

	@PreAuthorize("hasAnyAuthority('DEV')")
	@RequestMapping("/product/insert")
	public Result<String> insertProduct(@Validated @NotEmpty(message = "不能为空") @RequestParam("name") String name) {
		try {
			packageManagerServiceImpl.insertProduct(name);
			return Result.success("保存成功!");
		} catch (DataIntegrityViolationException e) {
			e.printStackTrace();
			return Result.fail(Result.CODE_SQL_ERROR, "重复保存");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Result.fail(Result.CODE_SQL_ERROR, "保存失败!");
	}

	@PreAuthorize("hasAnyAuthority('DEV')")
	@RequestMapping("/package/insert")
	public Result<String> insertPackage(@RequestParam("pid") long pid, @RequestParam("version") String version,
			@RequestParam("desc") String desc, @RequestParam("file") MultipartFile multipartFile) {
		try {
			ProductEntity productEntity = packageManagerServiceImpl.getProduct(pid);
			String fileName = multipartFile.getOriginalFilename();
			long date = DateUtils.getTime();
			String productName = productEntity.name;
			packageManagerServiceImpl.saveFile(multipartFile, productName, version);
			packageManagerServiceImpl.insertPackage(fileName, version, date, desc, productName, pid,
					multipartFile.getSize());
			return Result.success("上传成功!");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Result.fail(Result.CODE_GEN_TOKEN, "系统错误");
	}

	@PreAuthorize("hasAnyAuthority('DEV')")
	@RequestMapping("/package/delete")
	public Result<String> deletePackage(@RequestParam("id") long id) {
		try {
			packageManagerServiceImpl.deletePackage(id);
			return Result.success("删除成功!");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Result.fail(Result.CODE_GEN_TOKEN, "系统错误");
	}

	@PreAuthorize("hasAnyAuthority('DEV')")
	@RequestMapping("/package/update")
	public Result<String> updatePackage(@RequestParam("id") long id, @RequestParam("pid") long pid,
			@RequestParam("version") String version, @RequestParam("desc") String desc) {
		try {
			packageManagerServiceImpl.updatePackage(id, version, desc, desc, pid);
			return Result.success("修改成功!");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Result.fail(Result.CODE_GEN_TOKEN, "系统错误");
	}

	@RequestMapping("/package/download")
	public ResponseEntity<Resource> downloadPackageFile(@RequestParam("id") long id) {
		try {
			Resource resource = packageManagerServiceImpl.queryPackageFile(id);
			ResponseEntity<Resource> responseEntity = ResponseEntity.ok()
					.header("Content-Disposition",
							"attachment; filename=" + URLEncoder.encode(resource.getFile().getName(), "UTF-8"))
					.body(resource);
			return responseEntity;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@RequestMapping("/package/query")
	public Result<List<PackageEntityExt>> queryPackage(@RequestParam("id") long id, @RequestParam("page") int page) {
		try {
			return Result.success(packageManagerServiceImpl.getPackages(id, page));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Result.fail(Result.CODE_GEN_TOKEN, "系统错误");
	}
}
